<?php
/**
 * Created by PhpStorm.
 * User: Wangqing
 * Date: 2018/7/12
 * Time: 21:46
 */

namespace App\Common;

/*自定义类
 * **/
use Illuminate\Support\Facades\Request;
use Illuminate\Support\MessageBag;

class Helper
{
    /*
     * 引用无限级分类
     * @param Array $items
     * @return Array $tree
     */
    public static function generateTree($items)
    {
        $route = app('request')->route()->action['as'];
        $tree = array();
        foreach ($items as $item) {
            if (isset($items[$item['pid']])) {
                $items[$item['pid']]['child'][] = &$items[$item['id']];
                if ($route==$item['route']){
                    $items[$item['pid']]['active'] = true;
                    if($items[$item['pid']]['pid']){
                        $pid = $items[$item['pid']]['pid'];
                        $items[$pid]['active'] = true;
                    }
                }
            } else {
                if (!$item['pid']){
                    $tree[] = &$items[$item['id']];
                }
            }
        }
        return $tree;
    }

    /*
     * 引用无限级分类
     * @param Array $items
     * @return Array $tree
     */
    public static function generateTrees($items)
    {
        $tree = array();
        foreach ($items as $item) {
            if (isset($items[$item['pid']])) {
                $items[$item['pid']]['children'][] = &$items[$item['id']];
            } else {
                $tree[] = &$items[$item['id']];
            }

        }
        return $tree;
    }

    /**
     * 传递一个父级分类ID返回所有子分类ID
     * @param $cate array 全部分类数组
     * @param $pid int 父级ID
     * @param $flag int 是否包括父级自己的ID，默认不包括
     * @return array
     **/
    static public function getChildsId($cate, $pid, $flag = 0) {
        $arr = array();
        if ($flag) {
            $arr[] = $pid;
        }
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $arr[] = $v['id'];
                $arr = array_merge($arr , self::getChildsId($cate, $v['id']));
            }
        }

        return $arr;
    }
    /*
     * 递归无限级分类
     * @param Array $cate 全部分类数组
     * @param String $delimiter
     * @param  Integer $parent_id
     * @param  Integer $level
     * @param Array $arr
     */
     public static function toLevel($cate, $delimiter = '———', $parent_id = 0, $level = 0) {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $parent_id) {
                $v['level'] = $level + 1;
                ($level>0)?$v['delimiter'] =$delimiter:  $v['delimiter'] ='';
                $arr[] = $v;
                $arr = array_merge($arr, self::toLevel($cate, $delimiter, $v['id'], $v['level']));
            }
        }
        return $arr;

    }
    /*
     * 提交成功提示
     * @param string $message
     * @param  string $redirect
     * @param array $data
     * @return  $this|array
     */
    public static function success($message='',$redirect="",$data=[]){
        if(Request::ajax()){
            Request::session()->flash('message',$message);
            return [
                'status'=>true,
                'message'=>$message,
                'redirect'=>$redirect,
                'data'=>$data,
            ];
        }else
            return \Redirect::to($redirect)->with($message);
    }

    /*
     * 返回错误信息
     * @param $message
     * @param string $redirect
     * @param array $data
     * @return $this|array
     */
    public static function error($message='',$redirect="",$data=[]){
        if ($message instanceof MessageBag) {
            $message = $message->first();
        }
        if(Request::ajax())
            return [
                'status'=>false,
                'message'=>$message,
                'redirect'=>$redirect,
                'data'=>$data,
            ];
        else
            $message = new MessageBag([$message]);
        if(!empty($redirect)){
            return \Redirect::to($redirect)->withErrors($message);
        }else{
            return \Redirect::back()->withErrors($message);
        }
    }
    public static function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
        if(!is_int($length) || $length < 0) {
            return false;
        }
        $string = '';
        for($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $string;
    }

    public static function random($length, $numeric = FALSE) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }

    /**
     * @param $number
     * @return float|string
     * 格式化数字
     */
    public static function formatNumber($number){
        if (empty($number) || !is_numeric($number)) return $number;
        $unit = "";
        if ($number > 10000) {
            $leftNumber = floor($number / 10000);
            $rightNumber = round(($number % 10000) / 10000, 2);
            $number = floatval($leftNumber + $rightNumber);
            $unit = "w";
        } else {
            $decimals = $number > 1 ? 2 : 6;
            $number = (float)number_format($number, $decimals, '.', '');
        }
        return (string)$number . $unit;
    }

    /**
     * @param $end_at
     * @param $start_at
     * @return string
     * 时间差
     */
    public static function timeDiff($end_at,$start_at){
        $timediff = $end_at - $start_at;
        $remain = $timediff%86400;
        $hours = intval($remain/3600);

        $remain = $remain%3600;

        $mins = intval($remain/60);

        $secs = $remain%60;

        if($hours){
            $hours = sprintf('%02d',$hours);
        }else{
            $hours='00';
        }
        if($mins){
            $mins = sprintf('%02d',$mins);
        }else{
            $mins='00';
        }
        if($secs){
            $secs = sprintf('%02d',$secs);
        }else{
            $secs='00';
        }
        $replaytime = $hours.':'.$mins.':'.$secs;
        return $replaytime;
    }

    public static function desensitize($string, $start = 0, $length = 0, $re = '*')
    {
        if(empty($string) || empty($length) || empty($re)) return $string;
        $end = $start + $length;
        $strlen = mb_strlen($string);
        $str_arr = array();
        for($i=0; $i<$strlen; $i++) {
            if($i>=$start && $i<$end)
                $str_arr[] = $re;
            else
                $str_arr[] = mb_substr($string, $i, 1);
        }
        return implode('',$str_arr);
    }


    /**
     * 友好时间显示
     * @param $time
     * @return bool|string
     */
    public static function friend_date_one($time)
    {
        if (!$time)
            return false;
        $fdate = '';
        $d = time() - intval($time);
        $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
        $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
        $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
        $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
        $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
        $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
        $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
        if ($d == 0) {
            $fdate = '刚刚';
        } else {
            switch ($d) {
                case $d < $atd:
                    $fdate = date('Y年m月d日', $time);
                    break;
                case $d < $td:
                    $fdate = '后天' . date('H:i', $time);
                    break;
                case $d < 0:
                    $fdate = '明天' . date('H:i', $time);
                    break;
                case $d < 60:
                    $fdate = $d . '秒前';
                    break;
                case $d < 3600:
                    $fdate = floor($d / 60) . '分钟前';
                    break;
                case $d < $dd:
                    $fdate = floor($d / 3600) . '小时前';
                    break;
                case $d < $yd:
                    $fdate = '昨天' . date('H:i', $time);
                    break;
                case $d < $byd:
                    $fdate = '前天' . date('H:i', $time);
                    break;
                case $d < $md:
                    $fdate = date('m月d日 H:i', $time);
                    break;
                case $d < $ld:
                    $fdate = date('m月d日', $time);
                    break;
                default:
                    $fdate = date('Y年m月d日', $time);
                    break;
            }
        }
        return $fdate;
    }

    /**
     * 两时间之间的相差
     * @param $start_time
     * @param $end_time
     * @return string
     */
    public static function friend_date_two($start_time , $end_time){
        $sec = $start_time - $end_time;
        $sec = round($sec/60);
        $min = str_pad($sec%60, 2, 0, STR_PAD_LEFT);
        $hours_min = intval($sec/60);

        $time_format = $hours_min.":".$min;

        return $time_format;
    }
}